const util = require("./util");
//虚拟dom
class VElement {
	constructor(_this,tagName, props, children, events,ref) {
        this._$puz=_this;
		//保证只能通过如下方式调用：new VElement
		// if (!(this instanceof VElement)) {
		//     return new VElement(tagName, props, children,events);
        // }
        if(util.isString(props)){
            this.text=props;
            this.count = 0;
            this.tagName = tagName;
            return;
        }
		//可以通过只传递tagName和children参数
		if (util.isArray(props)) {
			children = [].concat(props);
			props = {};
		}
		// this.node=node;
		//设置虚拟dom的相关属性
		this.tagName = tagName;
        this.children = [].concat(children) || [];
        this.props = Object.assign({},props) || {};
        this.ref=ref;
		this.key = props ? props.key : void -1;
		this.events = events;
		var count = 0;
		util.each(this.children, function(child, i) {
			if (child instanceof VElement) {
				count += child.count;
			} else {
				children[i] = "" + child;
			}
			count++;
		});
		this.count = count;
	}
	//根据虚拟dom创建真实dom
	render() {
        if(this.tagName=='text'){
          return document.createTextNode(this.text)
        }
		//创建标签
        var el = document.createElement(this.tagName);
        if(this.ref){
            this._$puz.refs[this.ref]=el;
        }
		//设置标签的属性
		var props = this.props;
		for (var propName in props) {
			var propValue = props[propName];
			util.setAttr(el, propName, propValue);
		}
		if (this.events) {
			for (var key in this.events) {
				if (this.events.hasOwnProperty(key)) {
					function addListener(key,events){
						var event = events[key];
						el.addEventListener(key, (...params)=>{
							event.func.forEach(func => {
								func.apply(this,params)
							});
						}, event.flag);
					}
					addListener(key,this.events)
				}
			}
		}
		//一次创建子节点的标签
		util.each(this.children, function(child) {
			//如果子节点仍然为velement，则递归的创建子节点，否则直接创建文本类型节点
			el.appendChild(child.render());
		});
		return el;
    }
}

module.exports = VElement;
